c 標準庫中,有time 函數,可以返回 1970年1月1日 開始到現在的秒數,我們可以調用兩次的時間差來計算程式運行時間: https://github.com/yaowenxu/Workplace/blob/master/timer/timetimer.c NAME time -- get ti ...
c 標準庫中,有time 函數,可以返回 1970年1月1日 開始到現在的秒數,我們可以調用兩次的時間差來計算程式運行時間:
https://github.com/yaowenxu/Workplace/blob/master/timer/timetimer.c
NAME time -- get time of day LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <time.h> time_t time(time_t *tloc); DESCRIPTION The time() function returns the value of time in seconds since 0 hours, 0 minutes, 0 seconds, January 1, 1970, Coordinated Univer- sal Time, without including leap seconds. If an error occurs, time() returns the value (time_t)-1. The return value is also stored in *tloc, provided that tloc is non-null.time函數說明
/** * Author: Yaowen Xu * Github: https://github.com/yaowenxu * Organization: 北航系統結構研究所 * Date: 2019-08-18 13:03:53 * LastEditTime: 2019-08-18 13:14:33 * Description: 使用 C 語言庫 time 函數 對程式運行計時 以秒為單位 */ #include <time.h> #include <stdio.h> #include <math.h> int str2int(char* str){ char *p = str; int sum = 0; while (*p != '\0') { sum = sum*10 + (*p-'0'); p++; } return sum; } int main(int argc, char* argv[]){ time_t start, stop; // time_t aka long int def = 1000; if (argc == 2) { def = str2int(argv[argc-1]); } start = time(NULL); for (int i = 0; i < def ; i++) { float tmp = sqrt(i); } stop = time(NULL); time_t total = stop - start; // 使用運行的時間 以秒為單位 printf("Start: %ld s\n", start); printf("Stop: %ld s\n", stop); printf("Time: %ld s\n", total); // 總共使用的時鐘 return 0; }
保持更新,如果對您有幫助,請點擊推薦!更多關於C語言相關的知識,請關註 cnblogs.com/xuyaowen