曲径通幽论坛

标题: 获得 UNIX 时间戳毫秒 [打印本页]

作者: beyes    时间: 2013-11-5 23:08
标题: 获得 UNIX 时间戳毫秒
可以从 date 命令里获取 UNIX 时间戳,使用 %s 可以获得自 1970-01-01 00:00:00 以来的秒数;使用 %N 可以获得执行当前命令并显示结果时所经过的纳秒。因此,要获得 UNIX 时间戳的毫秒,那么可以执行下面的命令:
  1. UTIME=`date +%s%N`;
  2. echo`expr $UTIME/ 1000000`
复制代码
如果是 javascript ,那么使用 Date 对象的 getTime() 方法同样可以获得该毫秒时间戳。

还从网上照抄了段 C++ 程序:
[C++] 纯文本查看 复制代码
#include <time.h>
#include <sys/time.h>
#include <iostream>
#include <stdio.h>
using namespace std;

long long GetMillSec();

int main()
{
        long long nBegin = 0;
        long long nEnd = 0;

        nBegin = GetMillSec();

        struct timeval tv;
        gettimeofday(&tv,NULL);

        cout << "sec: " << tv.tv_sec << endl;                //秒
        cout << "u_sec: " << tv.tv_usec << endl;        //微秒
        cout << "m_sec: " << tv.tv_usec / 1000 << endl;

        /*time_t nSec = time((time_t*)NULL);
        cout << "time1:" << nSec << endl;

        time_t t2 = 0;
        time_t t3 = 0;
        t2 = time(&t3);

        cout << "time2:" << t2 << endl;
        cout << "time3:" << t3 << endl;*/

        for (int i = 0; i < 1000; i++)
        {
                int nSub = 0;
                nSub += i;
                int n = atoi("11111");

                cout << nSub << endl;
        }
       
        nEnd = GetMillSec();

        long long nSub = nEnd - nBegin;

        cout << "begin sec:" << nBegin << endl;
        cout << "end sec:" << nEnd << endl;
        cout << "sub Mill Sec1:" << nSub << endl;
        cout << "sub Mill Sec2:" << nEnd - nBegin << endl;

        return 0;
}

long long GetMillSec()
{
        long long nMillSec = 0;

        struct timeval tv;
        gettimeofday(&tv,NULL);

        nMillSec = (long long)tv.tv_sec * 1000;
        cout << "nMIllSec1 = " << nMillSec << endl;

        nMillSec += tv.tv_usec / 1000;
        cout << "nMIllSec2 = " << nMillSec << endl;

        return nMillSec;
}







欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2